<template>
  <Pages :current="1" :tab="false" class="s-page">
    <view class="page-header">
      <text class="header-title" @click="onJump">图片</text>
      <pagination :total="pageData.total" :pageSize="pageData.size" @change="onPage"></pagination>
      <!-- <CustomButton text="上传图片" backgroundColor="#409eff" @click="showMediaPicker" /> -->
    </view>

    <!-- 自定义弹窗 -->
    <media-picker ref="mediaPicker" @select="handleFileSelect" />

    <scroll-view class="tags-list" @refresherrefresh="handleRefresh" refresher-enabled :refresher-threshold="150"
      :refresher-triggered="refreshing">

      <view v-if="pageList.length === 0" class="empty-state">
        <text class="empty-text">暂无图片</text>
      </view>

      <view v-else class="tags-content">
        <view v-for="resource in pageList" :key="resource.id" class="tag-item" @longpress.stop="enterBatchMode">
          <!-- 添加选择框 -->
          <view v-if="batchMode" class="checkbox-wrapper">
            <view class="checkbox" :class="{ selected: selectedIds.has(resource.id) }"
              @click="toggleSelect(resource.id)" />
          </view>

          <view class="tag-image">
            <image :src="resource.small" mode="aspectFill" @click.stop="handlePreview(resource.url)" />
          </view>
          <view class="tag-actions">
            <CustomButton text="编辑" @click="handleEditResource(resource)" backgroundColor="#67c23a" />
            <CustomButton text="删除" @click="handleDeleteResource(resource)" backgroundColor="#f56c6c" />
          </view>
        </view>
      </view>
    </scroll-view>

    <MakePopup :visible="isImgModalVisible" ref="imgModal" @confirm="handleImgSave"
      @close="isImgModalVisible = false" />

    <!-- 底部批量操作菜单 -->
    <view v-if="showBatchMenu" class="batch-menu">
      <CustomButton text="全选" @click="toggleSelectAll(pageList)" />
      <CustomButton :text="`删除 (${selectedIds.size})`" backgroundColor="#f56c6c" :disabled="selectedIds.size === 0"
        @click="handleBatchDelete" />
      <CustomButton text="取消" @click="exitBatchMode" />
    </view>
  </Pages>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import CustomButton from '@/components/CustomButton.vue';
import Pages from '@/components/pages/index.vue';
import MediaPicker from '@/components/MediaPicker/MediaPicker.vue';
import { calculateMd5 } from "./tooler";
import { useDatabase } from './hooks/useDatabase';
import { useResource } from './hooks/useResource';
import MakePopup from './components/MakePopup.vue';
import pagination from '@/components/pagination.vue'

// const SERVER_URL = 'http://localhost:4500/uni-record/resources'; // 常量定义
const SERVER_URL = 'https://jsz315.xyz/uni-record/resources'; // 常量定义

// 新增引入
import useBatchSelect from './hooks/useBatchSelect'

// 在原有代码基础上添加
const {
  batchMode,
  selectedIds,
  showBatchMenu,
  enterBatchMode,
  toggleSelect,
  toggleSelectAll,
  exitBatchMode
} = useBatchSelect()

// 新增批量删除方法
const handleBatchDelete = async () => {
  if (selectedIds.size === 0) return

  uni.showModal({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedIds.value.size} 项吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // 这里需要根据你的API调整删除逻辑
          // await Promise.all([...selectedIds.value].map(id =>
          //   deleteResource(resources.value.find(r => r.id === id).md5)
          // ))
          await deleteImg([...selectedIds.value].join(","))
          exitBatchMode()
          reset(false)
          uni.showToast({ title: '删除成功', icon: 'success' })
        } catch (error) {
          uni.showToast({ title: '删除失败', icon: 'none' })
        }
      }
    }
  })
}

const mediaPicker = ref(null);
// const resources = ref([]);
const refreshing = ref(false);

const isImgModalVisible = ref(false);
const imgModal = ref(null);

function onPage(page) {
  console.log('onPage', page);
  loadMore(page);
}
function handlePreview(url) {
  uni.previewImage({
    urls: pageList.value.map(el => el.url),
    current: url
  });
}
async function handleImgSave(param) {
  isImgModalVisible.value = false;
  uni.showToast({ title: '创建中', icon: 'loading' });
  const obj = await createImage(param);
  if (obj?.length) {
    reset()
    console.log('创建成功', obj);
    uni.showToast({ title: '创建成功', icon: 'success' });
  }
  else {
    console.log('创建失败', obj);
    uni.showToast({ title: '创建失败', icon: 'none' });
  }
}

const { pageList,
  pageData,
  reset,
  createImage,
  deleteImg,
  loadMore } = useDatabase();
const { findByMd5 } = useResource(SERVER_URL);

onMounted(() => {
  reset();
  setTimeout(() => {
    console.log("mounted", pageList);
  }, 900);

});

function onJump() {
  uni.redirectTo({
    url: "/pages/Test/Lady"
  })
}

async function handleFileSelect(files) {
  for (const file of files) {
    try {
      const md5 = await calculateMd5(file);
      const existingResource = await findByMd5(md5);
      if (existingResource) {
        uni.showToast({ title: '文件已存在', icon: 'none' });
        handleRefresh();
        continue;
      }
      uploads(file.path, md5);
    } catch (error) {
      console.error('MD5计算失败:', error);
      uni.showToast({ title: 'MD5计算失败', icon: 'none' });
    }
  }
}


function handleEditResource(resource) {
  console.log("Editing resource:", resource);
  // 编辑逻辑
  isImgModalVisible.value = true;
  imgModal.value.open(resource.url);
}

function handleDeleteResource(resource) {
  uni.showModal({
    title: '确认删除',
    content: '确定要删除该资源吗？',
    success: async (res) => {
      if (res.confirm) {
        const rs = await deleteImg(resource.id);
        console.log("Deleting resource:", rs)
        if (rs?.rowNum) {
          uni.showToast({ title: '删除成功', icon: 'success' });
          reset(false)
        }
        else {
          uni.showToast({ title: '删除失败', icon: 'none' });
        }
      }
    }
  });
}

async function handleRefresh() {
  refreshing.value = true;
  await reset()
  refreshing.value = false;
}
</script>


<style lang="scss" scoped>
:deep(.uni-scroll-view-refresher) {
  background: none !important;
  margin-bottom: 20rpx;
}

.s-page {
  // height: 100vh;
  display: flex;
  padding: 20rpx;
  flex-direction: column;
  // .tags-list{
  //   flex: 1;
  // }
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  position: sticky;
  top: 0;
  z-index: 1;
  background: #f6f6f6;

  .header-title {
    font-size: 36rpx;
    font-weight: bold;
  }
}

.tags-list {

  .loading-state,
  .empty-state {
    // background: #fff;
    border-radius: 12rpx;
    padding: 48rpx;
    text-align: center;
    color: #909399;
    font-size: 28rpx;
  }

  .loading-state {
    background: transparent;
    margin: 20rpx 0;
  }

  .loading-more,
  .no-more {
    text-align: center;
    padding: 20rpx;
    color: #909399;
    font-size: 24rpx;
  }
}

.tags-content {
  display: grid;
  grid-template-columns: repeat(3, 1fr); // 一行3个
  gap: 16rpx;

  .tag-item {
    position: relative;
    // width: calc(50% - 8px); // 计算宽度以适应一行两列
    box-shadow: 0 4px 8px rgba(0, 0, 0, .1);
    border-radius: 8px;
    overflow: hidden;
    background-color: #fff;

    .tag-image {
      width: 100%;
      height: 200px; // 设置固定高度或其他合适的值

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .tag-actions {
      padding: 4px 0;
      display: flex;
      justify-content: space-around;
      background-color: #f9f9f9;

      button {
        flex: 1;
        // margin: 0 4px;
        padding: 2px;
        border: none;
        border-radius: 4px;
        color: #fff;
        font-size: 14px;
        cursor: pointer;
        transform: scale(0.8);
      }
    }
  }
}

/* 新增样式 */
.checkbox-wrapper {
  position: absolute;
  right: 8px;
  top: 8px;
  z-index: 2;
}

.checkbox {
  width: 30px;
  height: 30px;
  border: 2px solid #fff;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.5);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.checkbox.selected {
  background: #409eff;
  // border-color: #409eff;
  display: flex;
  justify-content: center;
  align-items: center;
  &::after {
    content: '';
    display: block;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: url("/static/icons/right.png") no-repeat center;
    background-size: contain;
  }
}

.batch-menu {
  z-index: 4;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(255, 255, 255, 0.95);
  padding: 16rpx;
  display: flex;
  justify-content: space-around;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
}
</style>